// pages/add/add.js
//格式化当前日期
const db=wx.cloud.database()
const photos=db.collection('photos')
var app=getApp()

//格式化当前日期
function formatDate(){
  var now = new Date()
  var year = now.getFullYear()
  var month = now.getMonth()+1
  var day = now.getDate()
  if (month<10)month = '0'+month
  if(day<10) day ='0'+day

  return year+'-'+month+'-'+day
}
Page({

  
  // 自定义函数--上传图片
  upload:function(){
  //选择图片
  wx.chooseImage({
    count:1,
    sizeType:['compressed'],
     sourceType:['album','camera'],
  success: function(res){
  //1oading提示框表示正在上传图片
  wx.showLoading({
    title: '上传中',
  })
  //获取图片临时地址
  const filePath= res.tempFilePaths[0]
  //自定义云端的图片名称
  const cloudPath= Math.floor(Math. random()*1000000)+filePath.match(/\.[^.]+?$/)[0]
  
  //上传图片到云存储空间中
  wx.cloud.uploadFile({
  cloudPath,
  filePath,
  success:res=>{
    //提示上传成功
    wx.showToast({
      title: '上传成功!',
    duration: 3000
    })
    //获取用户个人基础信息
    let userInfo= app.globalData.userInfo
    //获取当天日期
    let today=formatDate()
    //往云数据集中添加一条记录
   photos.add ({
     data:{
    photoUrl:res.fileID,
    avatarUrl:userInfo.avatarUrl,
    country:userInfo.country,
    province: userInfo.province,
    nickName: userInfo.nickName,
    addDate:today
  },
  success: res =>{
    console.log(res)
    },
    fail:e=>{
    console. log(e)
  }
})
  },
    fail: e=>{
    //提示上传失败
    wx.showToast({
      icon:'none',
    title:'上传失败',
    })
  }
})
  },
    fail: e=>{
    console.error(e)
    },
    complete:()=>{
    //上传完成后关闭 loading提示框
    wx.hideLoading()
    // 更新图片历史记录
    this.getHistoryPhotos()
  }
})
},
// 获取已上传图片历史记录
getHistoryPhotos:function(){
  let openid = app.globalData.openid
  // 获取当前用户的上传记录
  photos.where({
    _openid:openid
  }).get({
    success:res=>{
      this.setData({
        historyPhotos:res.data})
    }
  })
},

/**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(app.globalData.getUserInfo)
     //console.log(app.globalData.openid)
     this.getHistoryPhotos()
   },

})